package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.domain.StrategyTheme;
import cn.wolfcode.wolf2w.query.DestinationQuery;
import cn.wolfcode.wolf2w.query.StrategyQuery;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.repository.StrategyThemeRepository;
import cn.wolfcode.wolf2w.service.IDestinationService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyServiceImpl implements IStrategyService {


    @Autowired
    private StrategyRepository strategyRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StrategyCatalogRepository strategyCatalogRepository;

    @Autowired
    private StrategyThemeRepository strategyThemeRepository;

    @Autowired
    private IDestinationService destinationService;


    @Override
    public void insert(Strategy strategy) {
        strategyRepository.insert(strategy);
    }

    @Override
    public void delete(String id) {
        strategyRepository.deleteById(id);
    }

    @Override
    public void update(Strategy strategy) {
        strategyRepository.save(strategy);
    }

    @Override
    public Strategy get(String id) {
        //orElse方法从optional中取值，如果取不到返回null
        return strategyRepository.findById(id).orElse(null);
    }

    @Override
    public List<Strategy> list() {
        return strategyRepository.findAll();
    }

    @Override
    public Page<Strategy> query(StrategyQuery qo) {
//        //原始代码
//        Query query = new Query();
//        long totalcount = mongoTemplate.count(query, Strategy.class);
//        if(totalcount == 0){
//            //没有数据
//            return Page.empty();
//        }
//        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");
//        query.with(pageable);
//        List<Strategy> list = mongoTemplate.find(query, Strategy.class);
//        Page<Strategy> page =  new PageImpl<>(list, pageable, totalcount);
//        return page;

        Query query = null;
        if(StringUtils.hasLength(qo.getDestId())){
            query = new Query();
            Criteria c = Criteria.where("destId").is(qo.getDestId());
            query.addCriteria(c);
        }


        return DBHelper.query(mongoTemplate, Strategy.class, qo, query);
    }

    @Override
    public void saveOrUpdate(Strategy strategy) {

        //加入目的地ID
        StrategyCatalog strategyCatalog =  strategyCatalogRepository.findById(strategy.getCatalogId()).orElse(null);
        strategy.setDestId(strategyCatalog.getDestId());
        //加入目的地Name
        strategy.setDestName(strategyCatalog.getDestName());
        //加入主题名
        StrategyTheme strategyTheme = strategyThemeRepository.findById(strategy.getThemeId()).orElse(null);
        strategy.setThemeName(strategyTheme.getName());
        //分类名
        strategy.setCatalogName(strategyCatalog.getName());
        //查询国内，国外
        List<Destination>  destList = destinationService.queryToasts(strategy.getDestId());
        Destination rootDest = destList.get(0);
        if("中国".equals(rootDest)){
            //国内
            strategy.setIsabroad(Strategy.ABROAD_NO);
        }
        else {
            strategy.setIsabroad(Strategy.ABROAD_YES);//国外

        }


        if(!StringUtils.hasLength(strategy.getId())){
            //防止id为空串，直接写入到数据库，导致自动生成_id不成功
            strategy.setId(null);


            //添加创建时间
            strategy.setCreateTime(new Date());


            strategyRepository.save(strategy);
        }
        //修改
        else{

            //参数中的strategy是前台页面传递过来的用户录入的信息和隐藏的id
            //数据库中当前id对应的攻略对象
            Strategy currStrategy = strategyRepository.findById(strategy.getId()).orElse(null);
            strategy.setCreateTime(currStrategy.getCreateTime());
            strategy.setViewnum(currStrategy.getViewnum());
            strategy.setReplynum(currStrategy.getReplynum());
            strategy.setFavornum(currStrategy.getFavornum());
            strategy.setSharenum(currStrategy.getSharenum());
            strategy.setThumbsupnum(currStrategy.getThumbsupnum());
            strategyRepository.save(strategy);
        }
    }

    @Override
    public List<Strategy> viewnumTop3(String destId) {
        //viewnum top 3
        //按照viewnum排序，降序
        //取前三个
        //限定目的地
        Pageable pageable = PageRequest.of(0, 3, Sort.Direction.DESC, "viewnum");
        List<Strategy> list = strategyRepository.findByDestId(destId, pageable);
        return list;
    }


}
